#! /usr/bin/env python  
# -*- coding: utf-8 -*-  
# __author__ = "shuke"  
# Date: 2018/5/13  
import hashlib   
import pymysql  
from dbutils.pooled_db import PooledDB
import sys,os
sys.path.append(os.getcwd())
from src.utils.tool import Tool


# 下载文件
# 创建数据库连接池
tempPool = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数
    mincached=2,  # 初始化时，链接池中至少创建的空闲的链接
    maxcached=5,  # 链接池中最多闲置的链接
    maxshared=3,  # 链接池中最多共享的链接数量
    blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待
    host='192.168.10.191',
    port=3306,
    user='writer',
    password='zlc1002020',
    database='wisdom-exam-db',
    charset='utf8mb4'  # 设置编码
)

# 获取数据
def getScriptFiles():
    conn = tempPool.connection()
    cursor = conn.cursor()
    # 执行SQL语句
    sql = "SELECT id,path FROM script_files WHERE is_download = 0 ORDER BY id ASC limit 100"
    cursor.execute(sql)
    # 获取查询结果
    result = cursor.fetchall()
    # 不关闭连接，而是将连接放回连接池
    cursor.close()
    conn.close()
    return result

# 更新标识为下载    
def updateDownload(id,download_status):
    conn = tempPool.connection()
    cursor = conn.cursor()
    # 编写更新语句
    update_sql = "UPDATE script_files SET is_download = 1,download_status= %s WHERE id="+str(id)
    # 定义更新的值
    values = (download_status)
    # 执行更新语句
    cursor.execute(update_sql,values)
    # 提交事务
    conn.commit()
    # 关闭游标和数据库连接
    cursor.close()
    conn.close()

def run():
  i = 1
  root_path = 'D:/wwwroot/Python/resources/topics/'
  while i <= 50000:
    # 获取试题
    lists = getScriptFiles()      
    # id,path
    for row in lists:
        
        try:
            result = Tool.is_contained(str(row[1]),'http')
            if result == False: 
                updateDownload(row[0],'2')  
                continue

            file_url = str(row[1])
            file_url = Tool.str_replace(file_url,' ','')
            file_url = Tool.str_replace(file_url,'http://file.eep.qctchina.top/','https://fy.qctchina.com/question-acquisition-eec/')
            file_name = Tool.str_replace(file_url,'https://fy.qctchina.com/question-acquisition-eec/','')  # 不带域名的文件路径+文件名
            subName = Tool.get_file_name(file_url)  # 文件名
            filePaht = Tool.str_replace(file_name,subName,'') 
            filenamePaht = root_path+filePaht

            # 创建目录
            Tool.mkdir_directory(filenamePaht)
            # 下载文件
            # http://file.eep.qctchina.top/book-eec/thirdimport/20210312180729551013/images/1980650112678092800/1982097517160280073/image91.jpg
            # http://file.eep.qctchina.top/
            # https://fy.qctchina.com/question-acquisition-eec/
            # https://fy.qctchina.com/question-acquisition-eec/book-eec/thirdimport/202104091102581731016/images/1991804996211138560/1992130380119257089/image.jpg

            # str_replace(text,search_text,replace_text):
            # get_domain_with_protocol(url):
            # mkdir_directory(dir_path)

            result = Tool.download_file(file_url,root_path+file_name)
            if result :
                updateDownload(row[0],'1')    
            else:
                updateDownload(row[0],'2')  

            # https://static01.zlc100.com/topics

        except OSError as e:
            print(f"图片下载失败时出错: {e}")
            return False   
    
run()



    
    
    